package com.cheyun.netsalev3.viewmodel.aftersale

import android.app.Activity
import android.content.Intent
import android.view.View
import android.widget.DatePicker
import android.widget.TimePicker
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.cheyun.netsalev3.bean.CarBrandParam
import com.cheyun.netsalev3.bean.DialogParam
import com.cheyun.netsalev3.bean.aftersale.CarOwnerData
import com.cheyun.netsalev3.bean.aftersale.DriveDetail
import com.cheyun.netsalev3.bean.aftersale.DrivePlanData
import com.cheyun.netsalev3.bean.aftersale.EditDriveBack
import com.cheyun.netsalev3.bean.basedata.Member
import com.cheyun.netsalev3.repository.aftersale.EditDriveRepository
import com.cheyun.netsalev3.utils.FunctionUtils
import com.cheyun.netsalev3.utils.MySharedPreferences
import com.cheyun.netsalev3.view.aftersale.ChooseCarOwnerActivity
import com.cheyun.netsalev3.view.mars.choosecar.MarsChooseCarActivity
import com.cheyun.netsalev3.viewmodel.BaseViewModel
import com.cheyun.netsalev3.widget.DatePickerFragment
import com.cheyun.netsalev3.widget.MyContentDialog
import com.cheyun.netsalev3.widget.MyDialog
import com.cheyun.netsalev3.widget.TimePickerFragment
import com.jeremyliao.liveeventbus.LiveEventBus
import java.util.*
import kotlin.collections.ArrayList

class EditDriveActivityViewModel(var data: DriveDetail, var editDriveRepository: EditDriveRepository) : BaseViewModel() {
    var comtime: String = ""
    var activity: AppCompatActivity? = null

    var reservetime = MutableLiveData<String>()
    var sercivename = MutableLiveData<String>()
    var takecartypename = MutableLiveData<String>()

    var takecarphone = MutableLiveData<String>()
    var takecaraddress = MutableLiveData<String>()
    var arrivephone = MutableLiveData<String>()
    var arriveaddress = MutableLiveData<String>()

    var isLoading = false

    var isOrder = false
    var currentId = 0
    var currentView:View? = null
    var currentPlanData:DrivePlanData? = null

    fun onClickOk(view: View) {
        currentView = view
//        if(isLoading){
//            Toast.makeText(view.context, "正在提交中", Toast.LENGTH_LONG).show()
//            return;
//        }
        if (data.license.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入车牌号", Toast.LENGTH_LONG).show()
            return
        }
        if (data.vin.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入VIN", Toast.LENGTH_LONG).show()
            return
        }
        if (data.seriesname.isNullOrEmpty()) {
            Toast.makeText(view.context, "请选择车系", Toast.LENGTH_LONG).show()
            return
        }
        if (data.specname.isNullOrEmpty()) {
            Toast.makeText(view.context, "请选择车型", Toast.LENGTH_LONG).show()
            return
        }
        if (data.uname.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入客户姓名", Toast.LENGTH_LONG).show()
            return
        }
        if (data.phone.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入客户电话", Toast.LENGTH_LONG).show()
            return
        }
        if (data.reservetime.isNullOrEmpty()) {
            Toast.makeText(view.context, "请选择预约时间", Toast.LENGTH_LONG).show()
            return
        }
        if (data.sercivename.isNullOrEmpty()) {
            Toast.makeText(view.context, "请选择服务顾问", Toast.LENGTH_LONG).show()
            return
        }
        if (data.takecartype.isNullOrEmpty()) {
            Toast.makeText(view.context, "请选择取送车类型", Toast.LENGTH_LONG).show()
            return
        }
        if (data.takecarphone.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入起点电话", Toast.LENGTH_LONG).show()
            return
        }
        if (data.arrivephone.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入终点电话", Toast.LENGTH_LONG).show()
            return
        }
        if (data.takecaraddress.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入起点地址", Toast.LENGTH_LONG).show()
            return
        }
        if (data.arriveaddress.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入终点地址", Toast.LENGTH_LONG).show()
            return
        }


        var title = ""
        var onSuccess: (back:EditDriveBack) -> Unit = {
            currentId = it.takecarid

            if(!isOrder) {
                if(data.id !=0){
                    LiveEventBus.get().with("aftersale_drive_detail_refresh").postValue("")
                }
                isLoading = false
                MyToast(title)
                goList()
            }else{
                data.id = currentId
                //获取预估费用
                editDriveRepository.getPlanPrice(it.takecarid,this::getPlanBack)
            }
        }
        isLoading = true
        if (data.id == 0) {
            data.reservetype = "2"
            title = if(isOrder)"下单成功" else "添加成功"
            editDriveRepository.updateData(data, onSuccess)
        } else {
            title = "更新成功"
            editDriveRepository.updateData(data, onSuccess)
        }
    }

    fun getPlanBack(planData:DrivePlanData){
        currentPlanData = planData
        var context = currentView?.context
        if (context is AppCompatActivity) {
            var dialog = MyContentDialog.newInstance("提示",
                    "<br>预估费用:<span style='color:red'>"+planData.plantotalfee+"元</span><br>预估里程:<span style='color:red'>"+
                            planData.planmileage + "km</span><br>预估时间:<span style='color:red'>"+planData.plantime+"</span><br>商户剩余金额:<span style='color:red'>"+planData.usableMoney +"元</span><br>",true
            )
            dialog.onClickOk = this@EditDriveActivityViewModel::onClickPublish
            dialog.show(context?.supportFragmentManager, "")
        }
    }
    fun onClickPublish(){
        if(currentPlanData!=null) {
            editDriveRepository.drivePublishOrder(currentPlanData?.plantotalfee!!, currentPlanData?.planmileage!!, currentId, this::publishOrderBack)
        }
    }

    fun publishOrderBack(){
        MyToast("下单成功")
        LiveEventBus.get().with("aftersale_drive_detail_refresh").postValue("")
        goList()
    }

    fun goList(){
        LiveEventBus.get().with("aftersale_drive_refresh").postValue("")
        myFinish()
    }

    fun onClickOrder(view: View){
        isOrder = true
        onClickOk(view)
    }

    var dataShow = ObservableField<DriveDetail>(data)

    fun onClickCancel(view: View) {
        myFinish()
    }

    lateinit var content: AppCompatActivity

    /**
     * 离店
     */
    fun goTime(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            this.content = content
            var c = Calendar.getInstance()
            c.add(Calendar.DAY_OF_MONTH,1)
            var datePickerFragment = DatePickerFragment()
            datePickerFragment.minDate = Calendar.getInstance().timeInMillis
            datePickerFragment.maxDate = c.timeInMillis
            datePickerFragment.clickOk = this::goDateOk
            datePickerFragment.show(content.supportFragmentManager, "")
        }
    }

    var year1 = 0
    var month1 = 0
    var day1 = 0
    /**
     * 离店日期回调
     */
    fun goDateOk(view: DatePicker, year: Int, month: Int, day: Int) {
        this.year1 = year
        this.month1 = month
        this.day1 = day
        var timePickerFragment = TimePickerFragment()
        timePickerFragment.clickOk = this::goTimeOk
        timePickerFragment.show(content.supportFragmentManager, "")
    }

    /**
     * 离店时间回调
     */
    fun goTimeOk(view: TimePicker, hourOfDay: Int, minute: Int) {
        comtime = FunctionUtils.formatTime(year1.toString(), month1.toString(), day1.toString(), hourOfDay, minute)
        data.reservetime = comtime

        reservetime.postValue(comtime)
    }

    var memberlist = ArrayList<Member>()

    init {
//        MySharedPreferences.getBaseData()?.member?.apply {
//            memberlist.addAll(this)
//        }
        getMemberlist()
    }

    fun getMemberlist(){
        editDriveRepository.getAftersaleUsableUserList(this::getMemberBack)
    }
    fun getMemberBack(ms:List<Member>){
        memberlist.addAll(ms)
    }

    /**
     * 点击接待人员
     */
    fun onclickRcvname(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            var list = ArrayList<DialogParam>()
            for (item in memberlist) {
                if(item.isadmin == 0) {
                    var dialogParam = DialogParam(item.realname, item.uid.toString())
                    list.add(dialogParam)
                }
            }
            var myDialog = MyDialog.newInstance("请选择服务顾问", list)
            myDialog.huidia = this::rcvName
            myDialog.show(content.supportFragmentManager, "")
        }
    }

    /**
     * 接待人回调
     */
    fun rcvName(item: DialogParam?) {
        item?.apply {
            data.serciveuid = item.id
            data.sercivename = item.name

            var takecar = MySharedPreferences.getLoginData()?.channel?.settings?.takecar
            if(takecar!=null){
                var phone = takecar.cemservicephone!!

                if( data.takecartype.equals("1")){
                    //上门取车
                    data.arrivephone = phone
                    arrivephone.postValue(phone)
                }else if(data.takecartype.equals("2")){
                    //送车上门
                    data.takecarphone = phone
                    takecarphone.postValue(phone)
                }
            }


            sercivename.postValue(item.name)
        }
    }

    /**
     * 点击取送车类型
     */
    fun onclickTakecartype(view: View) {
        var content = view.context
        if (content is AppCompatActivity) {
            var list = ArrayList<DialogParam>()
            list.add(DialogParam("上门取车", "1"))
            list.add(DialogParam("送车上门", "2"))
            var myDialog = MyDialog.newInstance("请选择取送车类型", list)
            myDialog.huidia = this::takeCarTypeBack
            myDialog.show(content.supportFragmentManager, "")
        }
    }

    /**
     * 点击取送车类型回调
     */
    fun takeCarTypeBack(item: DialogParam?) {
        item?.apply {
            if(data.takecartype.equals(item.id))
                return
            data.takecartype = item.id
            data.takecartypename = item.name
            takecartypename.postValue(item.name)


            data.takecarphone = ""
            data.takecaraddress = ""
            data.arrivephone = ""
            data.arriveaddress = ""

            var address = MySharedPreferences.getLoginData()?.channel?.address!!

            var takecar = MySharedPreferences.getLoginData()?.channel?.settings?.takecar
            var gtakecarphone = ""
            if(takecar!=null){
                gtakecarphone = takecar.cemservicephone!!
            }

            if(item.id.equals("1")){
                //未选择“服务顾问”，选择“上门取车”类型：起点电话：默认回填为客户电话 ；终点电话为空；终点地址：默认为“经销商地址” ，起点地址为空
                //选择了“服务顾问”后，再选择“上门取车”类型：起点电话：默认回填为客户电话 ；终点电话：服务热线电话；终点地址：默认为“经销商地址” ，起点地址为空
                data.takecarphone = data.phone
                data.arriveaddress = address

                if(!data.serciveuid.isNullOrEmpty()){
                    data.arrivephone = gtakecarphone
                    arrivephone.postValue(gtakecarphone)
                }else{
                    arrivephone.postValue("")
                }

                takecarphone.postValue(data.phone)
                arriveaddress.postValue(address)

                takecaraddress.postValue("")
            }else{
                //选择了“服务顾问”后，再选择“送车上门“类型：终点电话：默认回填为客户电话 ；起点电话：服务热线电话；起点地址：默认为“经销商地址” ，终点地址为空
                //未选择“服务顾问”，    选择“送车上门“类型：终点电话：默认回填为客户电话 ；起点电话为空；起点地址：默认为“经销商地址” ，终点地址为空
                data.arrivephone = data.phone
                data.takecaraddress = address

                if(!data.serciveuid.isNullOrEmpty()){
                    data.takecarphone = gtakecarphone
                    takecarphone.postValue(gtakecarphone)
                }else{
                    takecarphone.postValue("")
                }

                arrivephone.postValue(data.phone)
                takecaraddress.postValue(address)

                arriveaddress.postValue("")
            }

        }
    }

    fun onClickSearchCepai(view: View){
        if (data.license.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入车牌号", Toast.LENGTH_LONG).show()
            return
        }
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(content, ChooseCarOwnerActivity::class.java)
            intent.putExtra("source","takecar")
            intent.putExtra("nkey","local")
            intent.putExtra("license",data.license)
            content.startActivityForResult(intent, 101)
        }
    }

    fun onClickSearchVin(view: View){
        if (data.engineno.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入发动机号", Toast.LENGTH_LONG).show()
            return
        }
        if (data.vin.isNullOrEmpty()) {
            Toast.makeText(view.context, "请输入VIN", Toast.LENGTH_LONG).show()
            return
        }
        var content = view.context
        if (content is AppCompatActivity) {
            var intent = Intent(content, ChooseCarOwnerActivity::class.java)
            intent.putExtra("source","takecar")
            intent.putExtra("nkey","all")
            intent.putExtra("engineno",data.engineno)
            intent.putExtra("vin",data.vin)
            content.startActivityForResult(intent, 101)
        }
    }

    /**
     * 品系
     */
    fun onClickBrandname(view: View) {
        if(data.reservetype.equals("1")) return
        var content = view.context
        if (content is AppCompatActivity) {
            var carBrandParam = CarBrandParam()
            var intent = Intent(content, MarsChooseCarActivity::class.java)
            intent.putExtra("car", carBrandParam)
            intent.putExtra("notop", true)
            intent.putExtra("Isspec", true)
            intent.putExtra("enableClickAll",true)
            content.startActivityForResult(intent, 102)
        }
    }

    /**
     * 品牌车系回调
     */
    fun setCarData(carBrandParam: CarBrandParam) {
        carBrandParam?.apply {
            data.seriesname = carBrandParam.seriesname
            data.specname = carBrandParam.specname
            data.brandgroup = carBrandParam.series + "," + carBrandParam.spec
        }
    }

    fun setCarOwner(carOwnerData:CarOwnerData){
        data.uname = carOwnerData.name
        data.phone = carOwnerData.phone
        data.vin = carOwnerData.vin
        data.engineno = carOwnerData.engineno
        data.license = carOwnerData.license
        data.series = carOwnerData.seriesid
        data.seriesname = carOwnerData.seriesname
        data.spec = carOwnerData.specid.toInt()
        data.specname = carOwnerData.specname

        data.brandgroup = carOwnerData.seriesid + "," + carOwnerData.specid

        data.engineno = carOwnerData.engineno
        dataShow.notifyChange()
    }



}